package com.example.feidaolumanager.viewModel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory.Companion.APPLICATION_KEY
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import com.example.feidaolumanager.MyApplication
import com.example.feidaolumanager.repository.UserPreferencesRepository
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch

/**
 * Created with IntelliJ IDEA.
 * @Author: Liao Run
 * @Date: 2024-02-21 14:58
 * @Description:
 **/
class SettingViewModel(private val userPreferencesRepository: UserPreferencesRepository) :
    ViewModel() {
    /**
     * 在 ViewModel 的伴生对象内，在 viewModelFactory initializer 块中，使用以下代码获取 DessertReleaseApplication 的一个实例
     */
    companion object {
        val Factory = viewModelFactory {
            initializer {
                val application = (this[APPLICATION_KEY] as MyApplication)
                SettingViewModel(application.userPreferencesRepository)
            }
        }
    }


    fun selectIfShowNavigationDialog(value: Boolean) {
        viewModelScope.launch {
            userPreferencesRepository.saveLayoutPreference(value)
        }
    }

    /**
     * 获取本地的布局设置
     */
    val isShowNavigationDialog: StateFlow<Boolean> =
        userPreferencesRepository.isShowNavigationDialog.map { isLinearLayout ->
            isLinearLayout
        }.stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5_000),
            initialValue = false // 默认点击地图上的点不弹导航窗口
        )
}